package com.future.lottie.audio;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.util.Log;

import java.util.Locale;
import java.util.UUID;

/**
 * @author xuchuanting
 * Create on 2020/9/10 17:25
 */
public class TextToSpeechMgr extends UtteranceProgressListener implements TextToSpeech.OnUtteranceCompletedListener {


    private static final String TAG = "TextToSpeachMgr";
    private static TextToSpeechMgr sInstance;
    private TextToSpeech mTextToSpeech;
    private boolean isSuccess;

    private TextToSpeechMgr() {
    }

    public static TextToSpeechMgr getInstance() {
        if (sInstance == null) {
            sInstance = new TextToSpeechMgr();
        }
        return sInstance;
    }

    public void playText(String text) {
        if (isEnable()) {
            mTextToSpeech.speak(text, TextToSpeech.QUEUE_ADD, null, UUID.randomUUID().toString());
        }
    }

    public boolean isEnable() {
        return mTextToSpeech != null && isSuccess;
    }

    public void stop(){
        if (isEnable()) {
            mTextToSpeech.stop();
        }
    }

    public void init(Context context) {
        mTextToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    int result = mTextToSpeech.setLanguage(Locale.CHINA);
                    mTextToSpeech.setPitch(1.0f);// 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
                    mTextToSpeech.setSpeechRate(1.0f);
                    mTextToSpeech.setOnUtteranceProgressListener(TextToSpeechMgr.this);
                    mTextToSpeech.setOnUtteranceCompletedListener(TextToSpeechMgr.this);
                    if (result == TextToSpeech.LANG_MISSING_DATA
                            || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        //系统不支持中文播报
                        isSuccess = false;
                    } else {
                        isSuccess = true;
                    }

                }
                Log.i(TAG, "onInit: " + status + isSuccess);
            }
        });
    }

    @Override
    public void onStart(String utteranceId) {
        Log.i(TAG, "onStart: " + utteranceId);
    }

    @Override
    public void onDone(String utteranceId) {
        Log.i(TAG, "onDone: " + utteranceId);
    }

    @Override
    public void onError(String utteranceId) {
        Log.i(TAG, "onError: " + utteranceId);
    }

    @Override
    public void onUtteranceCompleted(String utteranceId) {
        Log.i(TAG, "onUtteranceCompleted: " + utteranceId);
    }
}
